# 本因坊引擎网络模块
import json
import socket
import time
import threading
from ai.engine import Honinbo
from ai.data_center import Data_Center


class Server:
    # 创建一个tcp服务器
    honinbo = None

    def init(self):
        self.honinbo = Honinbo()

    def run_server(self, server, sock):

        while 1:
            # 这个数字必须他妈大点啊 不然妈的东西都收不到
            data = sock.recv(20000).decode()
            if data == "exit" or not data:
                break
            # 统一处理请求
            response = self.honinbo.parse_operator(data)
            sock.send(json.dumps(response).encode())
        sock.close()

    # 跑服务器
    def run(self, port):
        ip = "127.0.0.1"
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((ip, int(port)))
        server.listen(5)
        print("引擎运行在{}:{}".format(ip, port))
        # data_center = Data_Center()
        # data_center.get_all_data_set()
        # res = data_center.get_model_by_name('Tom')
        # print("len ->",len(res))
        while 1:
            sock, addr = server.accept()
            t = threading.Thread(target=self.run_server, args=(server, sock))
            t.start()
